package com.gpframework.module.manufacture.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.gpframework.common.enums.AuditStatusEnum;
import com.gpframework.common.enums.YesNoEnum;
import com.gpframework.common.utils.DateUtils;
import com.gpframework.common.utils.StringUtils;
import com.gpframework.module.manufacture.domain.GpMakingGoodsRequirementDetails;
import com.gpframework.module.manufacture.domain.GpProduceProduct;
import com.gpframework.module.manufacture.domain.GpProductionDetails;
import com.gpframework.module.manufacture.domain.req.GpProductionApplicationUpdate;
import com.gpframework.module.manufacture.domain.req.GpProductionDetailsAdd;
import com.gpframework.module.manufacture.service.*;
import com.gpframework.module.order.domain.GpProductDetails;
import com.gpframework.module.order.domain.req.GpProductDetailsAdd;
import com.gpframework.module.order.service.IGpProductDetailsService;
import com.gpframework.module.process.domain.GpProcessManagement;
import com.gpframework.module.process.domain.GpProcessScheduling;
import com.gpframework.module.process.domain.vo.GpProcessManagementVo;
import com.gpframework.module.process.service.IGpProcessDeliveryNoteService;
import com.gpframework.module.process.service.IGpProcessSchedulingService;
import com.gpframework.module.purchase.domain.GpPurchasingMakingDetails;
import com.gpframework.module.purchase.service.IGpPurchasingMakingDetailsService;
import org.apache.poi.ss.formula.functions.Now;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gpframework.module.manufacture.mapper.GpProductionApplicationMapper;
import com.gpframework.module.manufacture.domain.GpProductionApplication;
import com.gpframework.module.manufacture.domain.vo.GpProductionApplicationVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
/**
 * @ClassName GpProductionApplication
 * @Author gpframework
 * @Date 2023-12-04
 * @Version 1.0.0
 * @Description 缺货报库存申请Service业务层处理
 */
@Service
public class GpProductionApplicationServiceImpl extends ServiceImpl<GpProductionApplicationMapper, GpProductionApplication> implements IGpProductionApplicationService {

    @Autowired
    private IGpProductionDetailsService iGpProductionDetailsService;
    @Autowired
    private IGpProduceProductService iGpProduceProductService;
    @Autowired
    private IGpMakingGoodsRequirementDetailsService iGpMakingGoodsRequirementDetailsService;

    @Autowired
    private IGpProcessSchedulingService iGpProcessSchedulingService;
    @Autowired
    private IGpPurchasingMakingDetailsService iGpPurchasingMakingDetailsService;
    /**
     * @Description 查询列表返回VO 用于返回给前端的列表接口
     * @Author gpframework
     * @Date 2023-12-04
     * @Param [lqw]
     * @Return List<GpProductionApplicationVo>
     */
    @Override
    public List<GpProductionApplicationVo> listVo(QueryWrapper<GpProductionApplication> lqw) {
        return this.baseMapper.listVo(lqw);
    }

    /**
     * @Description 通过查询详情VO 用于返回给前端的列详情接口
     * @Author gpframework
     * @Date 2023-12-04
     * @Param [id]
     * @Return GpProductionApplicationVo
     */
    @Override
    public GpProductionApplicationVo getVoById(Long id) {
        return this.baseMapper.getVo(id);
    }

    @Override
    public boolean add(GpProductionApplication gpProductionApplication) {
        gpProductionApplication.setSn(getApplicationSn());
        return this.save(gpProductionApplication);
    }

    /**
     * 审核
     * @param gpProductionApplicationUpdate
     * @return
     */
    @Override
    @Transactional
    public boolean audit(GpProductionApplicationUpdate gpProductionApplicationUpdate) {
        List<Long> ids = gpProductionApplicationUpdate.getIds();
        Date now = new Date();
        this.update(new UpdateWrapper<GpProductionApplication>()
                .set("audit_status", gpProductionApplicationUpdate.getAuditStatus())
                .set("audit_id", gpProductionApplicationUpdate.getAuditId())
                .set("audit_name", gpProductionApplicationUpdate.getAuditName())
                .set("audit_time", now)
                .set("audit_remarks", gpProductionApplicationUpdate.getAuditRemarks())
                .in("id", ids));
        if (StringUtils.equals(gpProductionApplicationUpdate.getAuditStatus(), AuditStatusEnum.OK.getKey())) {
            GpProductionApplication productionApplication;
            // 如果审核状态是‘好的’，生成采购/生产/加工单
            for (Long id : ids) {
                productionApplication = this.getById(id);
                productionApplication.setCreateBy(gpProductionApplicationUpdate.getCreateBy());
                int type = StringUtils.isNotBlank(productionApplication.getType()) ? Integer.parseInt(productionApplication.getType()) : 0;
                switch (type) {
                    case 1:
                        // 生产需求
                        this.createProductionDetails(productionApplication);
                        break;
                    case 2:
                        // 加工需求
                        this.createProcessDetails(productionApplication);
                        break;
                    case 3:
                        // 采购需求
                        this.createPurchasingDetails(productionApplication);
                        break;
                    default:
                        break;
                }
            }
        }
        return true;
    }

    // 生成生产做货明细
    private void createProductionDetails(GpProductionApplication productionApplication) {
        GpProductionDetails gpProductionDetails = new GpProductionDetails();
        if (StringUtils.isNotBlank(productionApplication.getCreateBy())) {
            gpProductionDetails.setCreateBy(productionApplication.getCreateBy());
        }
        gpProductionDetails.setProductionApplicationId(productionApplication.getId());
        gpProductionDetails.setSalesmanId(productionApplication.getApplicantId());
        gpProductionDetails.setSalesmanName(productionApplication.getApplicantName());
        gpProductionDetails.setApplicantId(productionApplication.getApplicantId());
        gpProductionDetails.setApplicantName(productionApplication.getApplicantName());
        gpProductionDetails.setApplicantTime(productionApplication.getCreateTime());
        gpProductionDetails.setQuantity(productionApplication.getQuantity());
        // 从产品基础表获取品名、颜色
        if (StringUtils.isNotBlank(productionApplication.getProductName()) && StringUtils.isNotBlank(productionApplication.getColour())) {
            GpProduceProduct gpProduceProduct = iGpProduceProductService.getOne(new LambdaQueryWrapper<GpProduceProduct>()
                    .eq(GpProduceProduct::getProductName, productionApplication.getProductName())
                    .eq(GpProduceProduct::getColour, productionApplication.getColour())
                    .eq(GpProduceProduct::getDelStatus, YesNoEnum.NO.getKey())
                    .last("limit 1"));
            if (gpProduceProduct == null) {
                gpProduceProduct = new GpProduceProduct();
                gpProduceProduct.setProductName(productionApplication.getProductName());
                gpProduceProduct.setColour(productionApplication.getColour());
                iGpProduceProductService.save(gpProduceProduct);
            }
            gpProductionDetails.setProduceProductId(gpProduceProduct.getId());
            gpProductionDetails.setProductName(gpProduceProduct.getProductName());
            gpProductionDetails.setColour(gpProduceProduct.getColour());
        }
        //从做货明细配置获取基础数据
        GpMakingGoodsRequirementDetails details = iGpMakingGoodsRequirementDetailsService.getOne(new LambdaQueryWrapper<GpMakingGoodsRequirementDetails>()
                .eq(GpMakingGoodsRequirementDetails::getProductName, productionApplication.getProductName())
                .eq(GpMakingGoodsRequirementDetails::getColour, productionApplication.getColour())
                .eq(GpMakingGoodsRequirementDetails::getDelStatus, YesNoEnum.NO.getKey())
                .last("limit 1"));
        if (details != null) {
            gpProductionDetails.setFactoryColourCode(details.getDyeingFactoryColour());
            gpProductionDetails.setGramWeight(details.getGramWeight());
            gpProductionDetails.setFeel(details.getFeel());
            gpProductionDetails.setLowerMachineWidth(details.getLowerMachineWidth());
        }
        iGpProductionDetailsService.save(gpProductionDetails);
    }

    // 生成加工排单表
    private void createProcessDetails(GpProductionApplication productionApplication) {
        GpProcessScheduling gpProcessScheduling = new GpProcessScheduling();
        if (StringUtils.isNotBlank(productionApplication.getCreateBy())) {
            gpProcessScheduling.setCreateBy(productionApplication.getCreateBy());
        }

        //排单日期
        gpProcessScheduling.setSchedulingDate(new Date());
        gpProcessScheduling.setSn(getSn());
        gpProcessScheduling.setApplicantId(productionApplication.getApplicantId());
        gpProcessScheduling.setApplicantMan(productionApplication.getApplicantName());
        gpProcessScheduling.setApplicantTime(productionApplication.getCreateTime());
        GpProcessManagement gpProcessManagement = new GpProcessManagement();
        gpProcessScheduling.setFlowerPattern(gpProcessManagement.getFlowerPattern());
        gpProcessScheduling.setProcessor(gpProcessManagement.getProcessorCode());
        gpProcessScheduling.setRemarks(gpProcessManagement.getRemarks());

        gpProcessScheduling.setProductionApplicationId(productionApplication.getId());

        gpProcessScheduling.setProductName(productionApplication.getProductName());
        gpProcessScheduling.setProductColor(productionApplication.getColour());


        iGpProcessSchedulingService.save(gpProcessScheduling);
    }

    /**
     * 获取生成加工订单号
     */
    private String getSn() {
        String sn = "";

        String yyMMdd = DateUtils.getDate("yyMMdd");
        sn += yyMMdd;

        GpProcessScheduling processScheduling = iGpProcessSchedulingService.getOne(new LambdaQueryWrapper<GpProcessScheduling>()
                .eq(GpProcessScheduling::getDelStatus, YesNoEnum.NO.getKey())
                .isNotNull(GpProcessScheduling::getSn)
                .gt(GpProcessScheduling::getCreateTime, DateUtils.getDate("yyyy-MM-dd 00:00:00"))
                .orderByDesc(GpProcessScheduling::getCreateTime)
                .last("limit 1"));
        if (processScheduling == null) {
            sn += "-1";
        } else {
            String substring = processScheduling.getSn().substring(processScheduling.getSn().lastIndexOf("-") + 1);
            int index = Integer.parseInt(substring) + 1;
            sn += "-" + index;
        }
        return sn;
    }

    /**
     * 获取缺货报库存申请单号
     */
    private String getApplicationSn() {
        String sn = "";

        String yyMMdd = DateUtils.getDate("yyMMdd");
        sn += yyMMdd;

        GpProductionApplication gpProductionApplication = this.getOne(new LambdaQueryWrapper<GpProductionApplication>()
                .eq(GpProductionApplication::getDelStatus, YesNoEnum.NO.getKey())
                .isNotNull(GpProductionApplication::getSn)
                .gt(GpProductionApplication::getCreateTime, DateUtils.getDate("yyyy-MM-dd 00:00:00"))
                .orderByDesc(GpProductionApplication::getCreateTime)
                .last("limit 1"));
        if (gpProductionApplication == null) {
            sn += "-1";
        } else {
            String substring = gpProductionApplication.getSn().substring(gpProductionApplication.getSn().lastIndexOf("-") + 1);
            int index = Integer.parseInt(substring) + 1;
            sn += "-" + index;
        }
        return sn;
    }

    // 生成采购做货明细
    private void createPurchasingDetails(GpProductionApplication productionApplication) {
        GpPurchasingMakingDetails gpPurchasingMakingDetails = new GpPurchasingMakingDetails();
        if (StringUtils.isNotBlank(productionApplication.getCreateBy())) {
            gpPurchasingMakingDetails.setCreateBy(productionApplication.getCreateBy());
        }
        gpPurchasingMakingDetails.setMerchandiser(productionApplication.getApplicantName());
        gpPurchasingMakingDetails.setEnteredId(productionApplication.getApplicantId());
        gpPurchasingMakingDetails.setEnteredMan(productionApplication.getApplicantName());
        gpPurchasingMakingDetails.setEnteredTime(productionApplication.getCreateTime());
        gpPurchasingMakingDetails.setProductionApplicationId(productionApplication.getId());
        gpPurchasingMakingDetails.setQuantity(productionApplication.getQuantity());
        gpPurchasingMakingDetails.setRelatedNeedNumber(productionApplication.getSn());
        // 从产品基础表获取品名、颜色
        if (StringUtils.isNotBlank(productionApplication.getProductName()) && StringUtils.isNotBlank(productionApplication.getColour())) {
            GpProduceProduct gpProduceProduct = iGpProduceProductService.getOne(new LambdaQueryWrapper<GpProduceProduct>()
                    .eq(GpProduceProduct::getProductName, productionApplication.getProductName())
                    .eq(GpProduceProduct::getColour, productionApplication.getColour())
                    .eq(GpProduceProduct::getDelStatus, YesNoEnum.NO.getKey())
                    .last("limit 1"));
            if (gpProduceProduct == null) {
                gpProduceProduct = new GpProduceProduct();
                gpProduceProduct.setProductName(productionApplication.getProductName());
                gpProduceProduct.setColour(productionApplication.getColour());
                iGpProduceProductService.save(gpProduceProduct);
            }
            gpPurchasingMakingDetails.setProductName(gpProduceProduct.getProductName());
            gpPurchasingMakingDetails.setProductColor(gpProduceProduct.getColour());
        }
        iGpPurchasingMakingDetailsService.save(gpPurchasingMakingDetails);
    }
}
